package net.xdclass.rbac_shiro.config;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.CollectionUtils;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.util.Set;

/**
 * Created whit IntelliJ IDEA
 * User:杨骏杰
 * Date:2021/2/16
 * Time:20:16
 * 自定义fi
 */
public class CustomRolesOrAuthorizationFilter extends AuthorizationFilter {

    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {
        Subject subject = this.getSubject(request, response);
        //获取当前访问路径所需要的角色集合
        String[] rolesArray = (String[])mappedValue;

        //判断集合是否为空，如果为空则没有角色限制，则放行
        if (rolesArray == null && rolesArray.length == 0) {
            return true;
        }

        //获取限制的角色集合
        Set<String> roles = CollectionUtils.asSet(rolesArray);
        //使用遍历的方法，判断是否有对应的角色，有则放行
        for(String role : roles){
            if(subject.hasRole(role)){
                return true;
            }
        }
        return false;
    }
}
